package ae.pcfc.cldos.online.web.controller.file;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.net.io.CopyStreamException;
import org.apache.commons.net.io.Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import ae.pcfc.cldos.online.common.delegate.FileHandlerDelegate;
import ae.pcfc.cldos.online.common.vo.FileVO;
import ae.pcfc.cldos.online.web.ViewPath;
import ae.pcfc.cldos.online.web.controller.base.BaseController;
import ae.pcfc.cldos.online.web.exception.ResourceNotFoundException;

/**
 * 
 * @author arosa
 *
 */
@Controller
public class FileRequestController extends BaseController {
	
	@Autowired
	@Qualifier("fileHandlerDelegate")
	private FileHandlerDelegate fileHandlerDelegate;
	
	@RequestMapping(ViewPath.__FILE+"/{fileId}")
	public void handleRequest(@PathVariable String fileId, HttpServletResponse response) throws IOException{
		
		Long lFileId = null;
		try{
			lFileId = Long.parseLong(fileId);
		} catch (NumberFormatException e){
			throw new ResourceNotFoundException();
		}
		
		FileVO fileVO = fileHandlerDelegate.getFileFromJavaStorageById(lFileId);
		
		writeFileToResponse(fileVO, response, false);
	}
	
	@RequestMapping(ViewPath.__GS_FILE+"/{fileId}")
	public void handleGSFileRequest(@PathVariable String fileId, HttpServletResponse response) throws Throwable{
		Long lFileId = null;
		try{
			lFileId = Long.parseLong(encryptionDelegate.decodeAndDecrypt(fileId));
		} catch (NumberFormatException e){
			throw new ResourceNotFoundException();
		}
		
		FileVO fileVO = fileHandlerDelegate.getFileFromGSStorageById(lFileId);
		
		writeFileToResponse(fileVO, response, true);
	}
	
	private void writeFileToResponse(FileVO fileVO, HttpServletResponse response, boolean fileForDownload) throws IOException{
		if(fileVO!=null){
			InputStream is = fileVO.getInputStream();
			java.io.OutputStream os  = response.getOutputStream();
			
			if(fileVO.getContentLength()!=null){
				response.setContentLength(fileVO.getContentLength().intValue());
				response.setBufferSize(fileVO.getContentLength().intValue());
			}
			
			if(fileForDownload){
				response.setHeader("Content-Type", "application/force-download");
				response.setHeader("Content-Disposition", "attachment; filename=\""+fileVO.getFileName()+"."
				+fileVO.getFileExt()+"\"");
			}
			try {
				Util.copyStream(is, os, 20480);
				//Util.co
			} catch (CopyStreamException e) {
				//e.printStackTrace();
			} finally {
				is.close();
				os.close();
			}
		} else {
			throw new ResourceNotFoundException();
		}
	}
}
